package com.heima.behavior.service.impl;

import com.heima.behavior.doc.ApLikesBehavior;
import com.heima.behavior.service.LikesBehaviorService;
import com.heima.model.behavior.dto.LikesBehaviorDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LogicException;
import com.heima.common.exception.ParamException;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.common.util.LoginUserInfo;
import com.heima.model.common.enums.BehaviorRedisKeyEnum;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class LikesBehaviorServiceImpl implements LikesBehaviorService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 点赞或取消点赞
     * @param dto
     */
    public void like(LikesBehaviorDto dto) {
        // 1. 检查参数
        if (dto.getArticleId() == null || dto.getType() == null) {
            throw new ParamException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 获取当前用户
        LoginUserInfo userInfo = UserInfoThreadLocal.get();
        if (userInfo == null) {
            throw new LogicException(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3. 构建点赞行为对象
        ApLikesBehavior likesBehavior = new ApLikesBehavior();
        likesBehavior.setUserId(userInfo.getId());
        likesBehavior.setArticleId(dto.getArticleId());
        likesBehavior.setType(dto.getType());
        likesBehavior.setCreatedTime(new Date());

        // 4. 根据操作类型执行点赞或取消点赞
        if (dto.getOperation() == 0) {
            // 点赞操作
            // 查询是否已经点赞过
            Query query = Query.query(Criteria.where("userId").is(userInfo.getId().intValue())
                    .and("articleId").is(dto.getArticleId())
                    .and("type").is(dto.getType()));

            ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
            if (one == null) {
                // 没有点赞记录，新增点赞
                mongoTemplate.save(likesBehavior);
            }
        } else {
            // 取消点赞操作
            Query query = Query.query(Criteria.where("userId").is(userInfo.getId().intValue())
                    .and("articleId").is(dto.getArticleId())
                    .and("type").is(dto.getType()));

            mongoTemplate.remove(query, ApLikesBehavior.class);
        }

        // 5. 更新Redis缓存
        String likeKey = BehaviorRedisKeyEnum.LIKES_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());

        if (dto.getOperation() == 0) {
            // 点赞操作，添加到Redis set中
            stringRedisTemplate.opsForSet().add(likeKey, String.valueOf(userInfo.getId()));
        } else {
            // 取消点赞操作，从Redis set中移除
            stringRedisTemplate.opsForSet().remove(likeKey, String.valueOf(userInfo.getId()));
        }
    }
}
